import React, { useState } from 'react';
import { useAiCorrectorStore } from '@/stores/useAiCorrectorStore';
import { ComplianceStatus, ComplianceType, RiskLevel } from '@/types/work';
import type { ComplianceItem, ProgressStatus } from '@/types/work';

const ItemSelector: React.FC = () => {
  const { 
    state, 
    selectItem, 
    deselectItem, 
    selectAllItems, 
    deselectAllItems,
    updateFilters
  } = useAiCorrectorStore();
  
  const [searchTerm, setSearchTerm] = useState(state.filters.searchTerm);
  const [typeFilter, setTypeFilter] = useState<ComplianceType | 'all'>(state.filters.type);
  const [progressFilter, setProgressFilter] = useState<ProgressStatus | 'all'>(state.filters.progressStatus);
  
  const handleSearch = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value;
    setSearchTerm(value);
    updateFilters({ searchTerm: value });
  };
  
  const handleTypeFilterChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    const value = e.target.value as ComplianceType | 'all';
    setTypeFilter(value);
    updateFilters({ type: value });
  };
  
  const handleProgressFilterChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    const value = e.target.value as ProgressStatus | 'all';
    setProgressFilter(value);
    updateFilters({ progressStatus: value });
  };
  
  const handleSelectAll = () => {
    selectAllItems();
  };
  
  const handleDeselectAll = () => {
    deselectAllItems();
  };
  
  const isItemSelected = (id: string) => {
    return state.selectedItems.some(item => item.id === id);
  };
  
  const toggleItemSelection = (item: ComplianceItem) => {
    if (isItemSelected(item.id)) {
      deselectItem(item.id);
    } else {
      selectItem(item);
    }
  };

  return (
    <div className="bg-card rounded-lg shadow-sm p-6">
      <div className="mb-6">
        <h2 className="text-xl font-semibold text-foreground mb-4">选择检查项</h2>
        
        <div className="flex flex-col md:flex-row gap-4 mb-4">
          {/* 搜索框 */}
          <div className="flex-1">
            <input
              type="text"
              placeholder="搜索检查项标题或描述..."
              className="w-full h-12 px-4 border border-input rounded-lg focus:outline-none focus:ring-2 focus:ring-ring bg-background text-foreground placeholder:text-muted-foreground"
              value={searchTerm}
              onChange={handleSearch}
            />
          </div>
          
          {/* 类型筛选 */}
          <div className="w-full md:w-48">
            <select
              className="w-full h-12 px-4 border border-input rounded-lg focus:outline-none focus:ring-2 focus:ring-ring bg-background text-foreground"
              value={typeFilter}
              onChange={handleTypeFilterChange}
            >
              <option value="all">所有类型</option>
              <option value={ComplianceType.RISK}>风险项</option>
              <option value={ComplianceType.GUARANTEE}>保障项</option>
            </select>
          </div>
          
          {/* 进度筛选 */}
          <div className="w-full md:w-48">
            <select
              className="w-full h-12 px-4 border border-input rounded-lg focus:outline-none focus:ring-2 focus:ring-ring bg-background text-foreground"
              value={progressFilter}
              onChange={handleProgressFilterChange}
            >
              <option value="all">所有进度</option>
              <option value="completed">已完成</option>
              <option value="in-progress">进行中</option>
              <option value="remediation">整改中</option>
            </select>
          </div>
        </div>
        
        {/* 选择操作和统计 */}
        <div className="flex justify-between items-center mb-4">
          <div className="flex gap-2">
            <button
              onClick={handleSelectAll}
              className="px-4 py-2 text-sm bg-secondary hover:bg-secondary/80 text-secondary-foreground rounded-lg transition-colors"
            >
              全选
            </button>
            <button
              onClick={handleDeselectAll}
              className="px-4 py-2 text-sm bg-secondary hover:bg-secondary/80 text-secondary-foreground rounded-lg transition-colors"
            >
              取消全选
            </button>
          </div>
          
          <div className="text-sm flex items-center gap-2">
            <span className="tag-status-active">
              已选择: {state.selectedItems.length}
            </span>
            <span className="tag-check-type">
              筛选结果: {state.filteredItems.length}
            </span>
          </div>
        </div>
      </div>
      
      {/* 检查项列表 */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 max-h-[500px] overflow-y-auto p-1">
        {state.filteredItems.map(item => (
          <div
            key={item.id}
            className={`border rounded-lg p-4 cursor-pointer transition-all ${
              isItemSelected(item.id) 
                ? 'border-primary bg-primary/5 shadow-sm' 
                : 'border-border hover:border-primary/50'
            }`}
            onClick={() => toggleItemSelection(item)}
          >
            <div className="flex justify-between items-start mb-2">
              <div className="flex gap-2">
                <span className="tag-check-type">
                  {item.compliance_type === ComplianceType.RISK ? '风险项' : '保障项'}
                </span>
                
                {item.compliance_type === ComplianceType.RISK && item.risk_level && (
                  <span className={
                    item.risk_level === RiskLevel.HIGH ? 'tag-severity-high' :
                    item.risk_level === RiskLevel.MEDIUM ? 'tag-severity-medium' :
                    'tag-severity-low'
                  }>
                    {item.risk_level === RiskLevel.HIGH ? '高风险' : 
                     item.risk_level === RiskLevel.MEDIUM ? '中风险' : 
                     item.risk_level === RiskLevel.LOW ? '低风险' : '不适用'}
                  </span>
                )}

            {item.compliance_type === ComplianceType.GUARANTEE && item.compliance_status && (
                  <span className={
                    item.compliance_status === ComplianceStatus.NON_COMPLIANT ? 'tag-severity-critical' :
                    item.compliance_status === ComplianceStatus.PARTIALLY_COMPLIANT ? 'tag-severity-medium' :
                    'tag-severity-low'
                  }>
                    {item.compliance_status === ComplianceStatus.NON_COMPLIANT ? '不满足' : 
                     item.compliance_status === ComplianceStatus.PARTIALLY_COMPLIANT ? '部分满足':
                     item.compliance_status === ComplianceStatus.FULLY_COMPLIANT ? '完全满足' : '不适用'}
                  </span>
                )}
              </div>
              
              <input
                type="checkbox"
                checked={isItemSelected(item.id)}
                onChange={() => {}} // Empty onChange handler to avoid React warning
                className="h-5 w-5 text-primary rounded focus:ring-ring"
                onClick={(e) => {
                  e.stopPropagation();
                  toggleItemSelection(item);
                }}
              />
            </div>
            
            <h3 className="text-base font-medium text-foreground mb-1 line-clamp-1">{item.title}</h3>
            <p className="text-sm text-muted-foreground line-clamp-2">{item.description}</p>
          </div>
        ))}
      </div>
      
      {state.filteredItems.length === 0 && (
        <div className="text-center py-8">
          <span className="tag-check-type">
            没有找到符合条件的检查项
          </span>
        </div>
      )}
    </div>
  );
};

export default ItemSelector;
